<?php
global $tripurl, $xml_element_name, $name, $xml_parser, $countImage;

// Request Yahoo! REST Web Service using
// HTTP POST with curl. PHP4/PHP5
// Allows retrieval of HTTP status code for error reporting
// Author: Jason Levitt
// February 1, 2006

	error_reporting(E_ALL);

	$lat = $_REQUEST['lat'];
	$lon = $_REQUEST['lon'];
	$proximity = $_REQUEST['distance'];

//	$activities = '11,39,31,41,10,33';
	$activities = '11,31,41';
	$version = '3';
//	$mediaFilterMode = 0x1;
	$mediaFilterMode = 0x0; // no filter
	$api_key = 'b5d1218f5af7c6da3ba3eea65b402f43';
	$secret = '2799dd827f79fd39';
	$postargs = '&version='.urlencode($version);

// this works
//$request = 'http://www.everytrail.com/api/trip';
//$postargs .= '&trip_id='.urlencode($trip_id);

// this works
//$request = 'http://www.everytrail.com/api/user/trips';
//$postargs .= '&user_id='.urlencode($user_id);

// this works
//$request = 'http://www.everytrail.com/api/activities';

// this works too - thanks to Chris McCarty chris@globalmotion.com
	$request   = 'http://www.everytrail.com/api/trip/search';
	$postargs .= '&lat='.urlencode($lat);
	$postargs .= '&lon='.urlencode($lon);
	$postargs .= '&media_filter_mode='.$mediaFilterMode;
	$postargs .= '&proximity='.urlencode($proximity);
	$postargs .= '&activities='.urlencode($activities);
	$postargs .= '&sort='.urlencode('proximity');

	$session = curl_init($request);

// Set the POST options.
	curl_setopt ($session, CURLOPT_POST, true);
	curl_setopt ($session, CURLOPT_POSTFIELDS, $postargs);
	curl_setopt ($session, CURLOPT_HEADER, true);
	curl_setopt ($session, CURLOPT_RETURNTRANSFER, true);
	curl_setopt ($session, CURLOPT_USERPWD,"$api_key:$secret"); 

// Do the POST and then close the session
	$response = curl_exec($session);
	curl_close($session);

// Get HTTP Status code from the response
	$status_code = array();
	preg_match('/\d\d\d/', $response, $status_code);

// Check for errors
	switch( $status_code[0] ) {
		case 200:
			// Success
			break;
		case 503:
			die('Your call to Yahoo Web Services failed and returned an HTTP status of 503. That means: Service unavailable. An internal problem prevented us from returning data to you.');
			break;
		case 403:
			die('Your call to Yahoo Web Services failed and returned an HTTP status of 403. That means: Forbidden. You do not have permission to access this resource, or are over your rate limit.');
			break;
		case 400:
			// You may want to fall through here and read the specific XML error
			die('Your call to Yahoo Web Services failed and returned an HTTP status of 400. That means:  Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.');
			break;
		default:
			die('Your call to Yahoo Web Services returned an unexpected HTTP status of:' . $status_code[0]);
	}

	// Get the XML from the response, bypassing the header
	if (!($xml = strstr($response, '<?xml'))) {
		$xml = null;
	}

	$xml_parser = xml_parser_create();
	xml_set_element_handler($xml_parser, "startElement", "endElement");
	xml_set_character_data_handler($xml_parser, "characterData");
	parse_xml($xml);

//
// xml parsing functions (referenced in xml setup above)
//
function parse_xml($kml){
	global $tripurl, $countImage, $xml_parser, $kml_outline;
	if (!xml_parse($xml_parser, $kml))   {
		die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), 
       		xml_get_current_line_number($xml_parser)));  
	}
}


function startElement($parser, $name, $attrs) {  
  global $tripurl, $countImage, $kml_outline, $elements, $xml_element_name, $num_placemarks, $num_elements, $num_points, $num_polygons, $num_linestrings;
  $xml_element_name = $name;
  if($name=='TRIP')  {
  	  echo "<br>";
  	  $countImage = 0;
  	  while (list($key, $val) = each($attrs)) {
  	  	if($key=='ID') $tripurl = "http://everytrail.com/view_trip.php?trip_id=$val";
  	  }
  }
/*
  if($name=='PICTURE') {
  	  while (list($key, $val) = each($attrs)) {
  	  	  echo "<img src='$val'/>"; 
  	  }
  }
*/
}

function sec2hms ($sec, $padHours = false) 
  {

    // start with a blank string
    $hms = "";
    
    // do the hours first: there are 3600 seconds in an hour, so if we divide
    // the total number of seconds by 3600 and throw away the remainder, we're
    // left with the number of hours in those seconds
    $hours = intval(intval($sec) / 3600); 

    // add hours to $hms (with a leading 0 if asked for)
    $hms .= ($padHours) 
          ? str_pad($hours, 2, "0", STR_PAD_LEFT). ":"
          : $hours. ":";
    
    // dividing the total seconds by 60 will give us the number of minutes
    // in total, but we're interested in *minutes past the hour* and to get
    // this, we have to divide by 60 again and then use the remainder
    $minutes = intval(($sec / 60) % 60); 

    // add minutes to $hms (with a leading 0 if needed)
    $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ":";

    // seconds past the minute are found by dividing the total number of seconds
    // by 60 and using the remainder
    $seconds = intval($sec % 60); 

    // add seconds to $hms (with a leading 0 if needed)
    $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);

    // done!
    return $hms;
    
  }
  
function characterData($parser, $data) { 
	global $tripurl, $xml_element_name, $num_coordinates, $num_latlon, $countImage;
	global $kml_outline, $min_lat,$min_lon,$max_lat,$max_lon;
	if($xml_element_name=='NAME'){
		
		echo "<br><b><a href='$tripurl' target='_blank'>$data</a></b>";
//		echo "<button type='button' onClick='window.open(".'"'.$tripurl.'"'.")'>$data</button>";
	}
	if($xml_element_name=='DESCRIPTION'){
		echo "<p>$data</p>";
	}
	if($xml_element_name=='THUMBNAIL'){
//		if($countImage<6) {
			$image = str_replace('thumbnail','fullsize',$data);
//			echo '<a href="'.$image.'" target="_blank"><img src='."'$data'/></a>";
			echo '<button type="button" onClick="imagePop('."'$image'".')"><img src='."'$data'/></button>";
			$countImage = $countImage + 1;
//		}
	}
//	if($xml_element_name=='GPX'){
//		echo '<button type="button" onClick="kmlOverlay('."'$data'".')">show on map</button>';
//		echo "<br>$data<br>";
//	}
//	if($xml_element_name=='KML'){
//		echo '<button type="button" onClick="kmlOverlay('."'$data'".')">show on map</button>';
//		echo "<br>$data<br>";
//	}
	if($xml_element_name=='DURATION'){
		if($data>0) {
			$duration = sec2hms($data,false);
			echo "<br>Duration: $duration<br>";
		}
	}
}

function endElement($parser, $name) {
  global $xml_element_name, $kml_outline;
}
?>
